<?php
// +----------------------------------------------------------------------
// | 系统用户业务
// +----------------------------------------------------------------------
namespace app\admin\service;

use app\common\model\SysRoleModel;
use app\common\service\SysRoleService as CommonSysRoleService;
use app\common\enum\BaseStatusEnum;
use app\common\enum\ErrorEnum;
use app\common\service\SysRoleMenuService as CommonRoleMenuService;
use app\common\service\SysMenuService;

class SysRoleService {
    /**
     * 分页
     * @param  array  $param  请求参数
     * @return array
     */
    public static function page($param){
        $pageData = SysRoleModel::page($param);

        foreach ($pageData as $k => $v) {
            $v['statusName'] = BaseStatusEnum::getDescription($v['status']);
        }

        return $pageData;
    }

    /**
     * 列表
     * @return array
     */
    public static function list(){
        return SysRoleModel::where('status', BaseStatusEnum::ENABLED)->select()->toArray();
    }

    /**
     * 新增数据
     * @param  array  $data  新增的数据
     * @return json
     */
    public static function save($data){
        if(SysRoleModel::getByRoleName($data['role_name'])){
            return failure(ErrorEnum::ROLE_NAME_IS_EXIST_CODE, ErrorEnum::ROLE_NAME_IS_EXIST_DESC);
        }

        return CommonSysRoleService::save($data);
    }

    /**
     * 更新数据
     * @param  array  $data  更新的数据
     * @return json
     */
    public static function update($data){
        $info = SysRoleModel::find($data['id']);
        if(!$info){
            return failure(ErrorEnum::F_IS_NOT_EXIST_CODE, ErrorEnum::F_IS_NOT_EXIST_DESC);
        }

        $info->save($data);
        return $info->id;
    }

    /**
     * 详情
     * @param  array  $id  数据ID
     * @return json
     */
    public static function info($id){
        return CommonSysRoleService::info($id);
    }

    /**
     * 删除
     * @param  string  $ids  数据ID
     * @return json
     */
    public static function destroy($ids){
        if(!empty($ids)){
            SysRoleModel::deleteById($ids);
        }
    }

    /**
     * 授权
     * @param  array  $data  
     * @return json
     */
    public static function authorize($data){
        $list = [];
        foreach ($data['menus'] as $menuId) {
            array_push($list, ['role_id' => $data['id'], 'menu_id' => $menuId]);
        }
        if ($list) {
            CommonRoleMenuService::destroyByRoleId($data['id']);
            CommonRoleMenuService::saveAll($list);
        }
    }

    /**
     * 获取权限
     * @param  array  $ids  角色ID
     * @return json
     */
    public static function getPermissions($ids){
        return CommonRoleMenuService::listByRoleIds($ids);
    }

}